package com.bestcem.xm.cjm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializeConfig;
import lombok.experimental.UtilityClass;

import java.util.HashMap;
import java.util.Map;

@UtilityClass
public class SnakeFastJsonUtil {

    /**
     * 将驼峰形式的bean转化为蛇形json
     *
     * @param item
     * @return java.lang.String
     * @author chenglong.yue <chenglong.yue@idiaoyan.com>
     * @date 2023/2/7 15:06
     */
    public String toSnakeJsonStr(Object item) {
        //使用单例模式，避免性能问题
        SerializeConfig config = SerializeConfigSingleton.getInstance();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        return JSON.toJSONString(item, config);
    }

    /**
     * 将驼峰形式的bean转化为蛇形map
     *
     * @param item
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author chenglong.yue <chenglong.yue@idiaoyan.com>
     * @date 2023/2/7 15:08
     */
    public Map<String, Object> toSnakeMap(Object item) {
        return JSON.parseObject(toSnakeJsonStr(item), new TypeReference<HashMap<String, Object>>() {
        });
    }

    /**
     * 将驼峰形式的bean转化为蛇形JSONObject
     *
     * @param item
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author chenglong.yue <chenglong.yue@idiaoyan.com>
     * @date 2023/2/7 15:08
     */
    public JSONObject toSnakeJsonObject(Object item) {
        return JSON.parseObject(toSnakeJsonStr(item));
    }
}
